package com.health.viewscontrols.medical.device.ecg;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.ScanResult;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.contec.pm10.code.bean.DeviceParameter;
import com.contec.pm10.code.bean.EcgData;
import com.contec.pm10.code.bean.SdkConstants;
import com.contec.pm10.code.callback.BluetoothSearchCallback;
import com.contec.pm10.code.callback.ConnectCallback;
import com.contec.pm10.code.callback.DataInformationCallback;
import com.contec.pm10.code.callback.GetSingleDataCallback;
import com.contec.pm10.code.connect.ContecSdk;
import com.health.httpbean.model.EcgModel;
import com.health.viewscontrols.medical.PhotoViewActivity;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.hqxd.HQXDActivity;
import com.novabluetooth.services.libecg.ecgdemo.MainPC80B;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import javax.security.auth.login.LoginException;

public class ECGPM10Activity extends BaseDeviceActivity {

    private ContecSdk contecSdk = null;
    private BluetoothDevice bluetoothDevice = null;
    private EcgData mEcgData;
    private String imgUrl;
    private boolean isDisConn = false;

    @Override
    public void doBusiness() {
        tv_bind_device.setVisibility(View.INVISIBLE);
        tv_operation_tips.setText(com.nova.health.ble.R.string.bf_ecg);
        bt_start.setText("获取测量结果");
        initSdk();

    }

    private void initSdk() {
        contecSdk = new ContecSdk(getApplicationContext());
        contecSdk.init(false);
    }

    @Override
    public void onWidgetClick(View view) {
        super.onWidgetClick(view);
        if (view.getId() == com.nova.health.ble.R.id.bt_start) {
            startDevice();

        }
    }

    @Override
    public void startDevice() {
//        showProgressDialog("正在连接" + deviceEnum.getTitle());
        contecSdk.startBluetoothSearch(new BluetoothSearchCallback() {
            @Override
            public void onScanResult(ScanResult scanResult) {
                Log.e(TAG, "onScanResult: " + scanResult.getDevice().getName() );
                bluetoothDevice = scanResult.getDevice();
                if ((bluetoothDevice.getName().contains("PM10") || bluetoothDevice.getName().contains("PM20"))&& contecSdk != null){
                    contecSdk.connect(bluetoothDevice, mConnectCallback); //蓝牙连接设备
                    contecSdk.stopBluetoothSearch();
                }
            }

            @Override
            public void onScanError(int i) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        blueToothState.setText("未找到PM10心电设备");
                    }
                });
            }

            @Override
            public void onScanComplete() {

            }
        }, 2000);
    }

    /**
     * 连接状态回调
     */
    ConnectCallback mConnectCallback = new ConnectCallback() {
        @Override
        public void onConnectStatus(final int status) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e(TAG, "status = " + status);
                    if (status == SdkConstants.CONNECT_CONNECTED) {
                        blueToothState.setText("蓝牙连接成功");
                        getDataInformation();
//                        showProgressDialog("请测量15s点击获取结果");
                    } else if (status == SdkConstants.CONNECT_DISCONNECTED || status == SdkConstants.
                            CONNECT_DISCONNECT_SERVICE_UNFOUND || status == SdkConstants.CONNECT_DISCONNECT_NOTIFY_FAIL) {
                        blueToothState.setText("蓝牙设备已断开");
                        if (!isDisConn && bluetoothDevice != null && contecSdk != null) {
                            startDevice();
                        }
                    } else if (status == SdkConstants.CONNECT_DISCONNECT_EXCEPTION) {
                        blueToothState.setText("蓝牙设备已断开");
                        if (!isDisConn && bluetoothDevice != null && contecSdk != null) {
                            startDevice();
                        }
                    }
                }
            });
        }

        /**
         * usb打开状态回调
         * @param status
         */
        @Override
        public void onOpenStatus(final int status) {
        }
    };

    @Override
    public void disconnectDevice() {
        Log.e(TAG, "disconnectDevice: " );
        if (contecSdk != null) {
            isDisConn = true;
            contecSdk.disconnect();
            bluetoothDevice = null;
        }
    }



    @Override
    public void update(String hexStr) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0x1001) {
                String heartRate = data.getStringExtra("heartRate");
                String hrResult = data.getStringExtra("hrResult");
                String ecgImgUrl = data.getStringExtra("ecgImgUrl");
                if (!TextUtils.isEmpty(heartRate)) {
                    Log.e(TAG, "onActivityResult: " + heartRate + hrResult);
                    tv_result.setText("测量结果：心率 " + heartRate + "\n" + "" + hrResult);

                    EcgModel ecgModel = new EcgModel();
                    ecgModel.setHr(heartRate + "");
                    ecgModel.setEcgResult(hrResult);
                    ecgModel.setEcgImg(ecgImgUrl);
                    Log.e(TAG, "onActivityResult: " + ecgModel.toString());
                    DeviceShowSaveData.saveEcg(GsonUtils.toJson(ecgModel));
                    if (!TextUtils.isEmpty(ecgImgUrl)) {
                        try {
                            Bitmap bitmap = getLocalBitmap(ecgImgUrl);
                            show_img.setImageBitmap(bitmap);
                            show_img.setVisibility(View.VISIBLE);
                            showPhotoView(ecgImgUrl);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Log.e(TAG, "onActivityResult: " + heartRate + hrResult);
                    tv_result.setText("未测量，请测量心电");
                }

            }
        }
    }


    public Bitmap getLocalBitmap(String url) {

        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void showPhotoView(String ecgImgUrl) {
        if (!TextUtils.isEmpty(ecgImgUrl)) {
            show_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(ECGPM10Activity.this, PhotoViewActivity.class)
                            .putExtra("imgUrl", ecgImgUrl));
                }
            });
        } else {
            ToastUtils.showShort("图片不能为空");
        }
    }

    private void getDataInformation() {
        contecSdk.getDataInformation(DeviceParameter.DataType.ORDERNUMBER, new DataInformationCallback() {
            @Override
            public void onFail(final int errorCode) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "run: "+ errorCode );
//                        tvGetDataInfo.setText("errorCode = " + errorCode);
                    }
                });
            }

            @Override
            public void onSuccess(final ArrayList<EcgData> ecgDataArrayList) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        for (int i = 0; i < ecgDataArrayList.size(); i++) {
                            Log.e(TAG, "uploadCount = " + ecgDataArrayList.get(i).getUploadCount());
                            Log.e(TAG, "currentCount = " + ecgDataArrayList.get(i).getCurrentCount());
                            Log.e(TAG, "orderNumber = " + ecgDataArrayList.get(i).getOrderNumber());
                            Log.e(TAG, "uploadStatus = " + ecgDataArrayList.get(i).getUploadStatus());
                            Log.e(TAG, "leadNum = " + ecgDataArrayList.get(i).getLeadNumber());
                            Log.e(TAG, "size = " + ecgDataArrayList.get(i).getSize());
                            Log.e(TAG, "pr = " + ecgDataArrayList.get(i).getPr());
                            Log.e(TAG, "year = " + ecgDataArrayList.get(i).getYear());
                            Log.e(TAG, "month = " + ecgDataArrayList.get(i).getMonth());
                            Log.e(TAG, "day = " + ecgDataArrayList.get(i).getDay());
                            Log.e(TAG, "hour = " + ecgDataArrayList.get(i).getHour());
                            Log.e(TAG, "min = " + ecgDataArrayList.get(i).getMin());
                            Log.e(TAG, "sec = " + ecgDataArrayList.get(i).getSec());
                            Log.e(TAG, "sec = " + ecgDataArrayList.get(i).getChineseResult());
                        }
                        if (ecgDataArrayList != null && ecgDataArrayList.size() > 0) {
                            getSingleData(ecgDataArrayList.get(ecgDataArrayList.size()-1).getOrderNumber());
                        }
                    }
                });
            }
        });
    }

    private void getSingleData(int orderNumber) {
        contecSdk.getSingleData(orderNumber, new GetSingleDataCallback() {
            @Override
            public void onFail(final int errorCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "获取单条数据超时");
//                        tvGetSingleData.setText("errorCode = " + errorCode);
                    }
                });
            }

            /**
             * 获取单条数据回调
             * @param arrayList
             */
            @Override
            public void onSingleData(final ArrayList<Integer> arrayList) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

//                        tvGetSingleData.setText("size = " + arrayList.size());
                        mEcgData = new EcgData();
                        mEcgData.setLeadNumber(0);
                        int[] ints = new int[arrayList.size()];
                        for (int i = 0; i < arrayList.size(); i++) {
                            ints[i] = arrayList.get(i);
                        }
                        mEcgData.setEcgDataBean(ints);
                    }
                });
            }

            @Override
            public void onSingleData(final EcgData ecgData) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mEcgData = ecgData;
                        Log.e(TAG, "单条数据接收完毕");
                        Log.e(TAG, "单条数据接收完毕" + mEcgData.getPr());
                        Log.e(TAG, "单条数据接收完毕" + mEcgData.getChineseResult());

                        tv_result.setText("测量结果：心率 " + mEcgData.getPr() + "\n" + "" + mEcgData.getChineseResult());

                        EcgModel ecgModel = new EcgModel();
                        ecgModel.setHr(mEcgData.getPr() + "");
                        ecgModel.setEcgResult("");
                        ecgModel.setEcgImg("");
                        Log.e(TAG, "onActivityResult: " + ecgModel.toString());
                        DeviceShowSaveData.saveEcg(GsonUtils.toJson(ecgModel));
//                        if (!TextUtils.isEmpty(ecgImgUrl)) {
//                            try {
//                                Bitmap bitmap = getLocalBitmap(ecgImgUrl);
//                                show_img.setImageBitmap(bitmap);
//                                show_img.setVisibility(View.VISIBLE);
//                                showPhotoView(ecgImgUrl);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
                    }
                });
            }

            @Override
            public void onProgress(final int progress) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        tvGetSingleData.setText("progress = " + progress);
//                    }
//                });
            }
        });
    }
}
